package com.sky.controller.user;

import com.sky.constant.StatusConstant;
import com.sky.entity.Dish;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController("userDishController")
@Api(tags = "查询菜品")
@RequestMapping("/user/dish")
@Slf4j
public class DishController {
    @Autowired
    DishService dishService;
    @Autowired
    RedisTemplate redisTemplate;
    /**
     * 根据分类ID查询在售的菜品
     * @param categoryId
     * @return
     */
    @GetMapping("/list")
    public Result<List<DishVO>> list(Long categoryId){
        log.info("根据分类ID查询在售的菜品");
        //构建redis中的key，规则dish_categoryId
        String key = "dish_"+categoryId;
        ValueOperations ops = redisTemplate.opsForValue();
        //查询redis中是否存在菜品数据
        List<DishVO> dishVOList = (List<DishVO>) ops.get(key);
        //存在，直接查询redis
        if (dishVOList!=null&&dishVOList.size()>0){
            return Result.success(dishVOList);
        }
        //不存在，继续查询数据库，并添加到redis

        //根据分类ID查询在售的菜品
        Dish dish = Dish.builder()
                .categoryId(categoryId)
                .status(StatusConstant.ENABLE)
                .build();
        dishVOList = dishService.listWithFlavor(dish);
        //添加到redis
        ops.set(key,dishVOList);
        return Result.success(dishVOList);
    }
}
